﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using MacomberMapSystem.Common.CIM;
using System.Drawing;
using System.IO;
using MacomberMapSystem.Common.Properties;
using MacomberMapSystem.Common.Database;
using MacomberMapSystem.Common.Internals;

namespace MacomberMapSystem.Common.Integration
{
    /// <summary>
    /// The data manager holds all data connections and UI forms
    /// </summary>
    public static class Data_Manager
    {
        #region Variable declarations
        /// <summary>Our main panel for docking purposes</summary>
        public static DockPanel MainDock;

        /// <summary>Our collection of KV Levels</summary>
        public static MM_Indexed_Dictionary<String, MM_KVLevel> KVLevels = new MM_Indexed_Dictionary<string, MM_KVLevel>(10);

        #endregion

        #region Form display
        /// <summary>
        /// Create a thread pool to display a form
        /// </summary>
        /// <param name="FormType">The type of form</param>
        /// <param name="Title">The title of the form</param>
        /// <param name="State">The docking state of the form</param>
        /// <param name="Parameters">The paramters for the form's initialization</param>
        public static DockContent DisplayForm(Type FormType, String Title, DockState State, params object[] Parameters)
        {
            DockContent FormToDisplay = Activator.CreateInstance(FormType, Parameters) as DockContent;
            FormToDisplay.Text = Title;
            FormToDisplay.Show(MainDock, State);
            return FormToDisplay;
        }
        #endregion

        /// <summary>
        /// Locate a KV Level for a particular CIM element
        /// </summary>
        /// <param name="Elem">The voltage level to check</param>
        /// <returns></returns>
        public static MM_KVLevel LocateKVLevel(CIM_Element Elem)
        {
            if (Elem == null)
                return null; //MM_Overall_Display.KVLevels["Other KV"];
            else if (KVLevels.ContainsKey(Elem.Name))
                return KVLevels[Elem.Name];
            else if (KVLevels.ContainsKey(Elem.Name + " KV"))
                return KVLevels[Elem.Name + " KV"];
            else
                return KVLevels["Other KV"];
        }

        /// <summary>
        /// Report a KV level
        /// </summary>
        /// <param name="KVLevel"></param>
        /// <returns></returns>
        public static MM_KVLevel LocateKVLevel(String KVLevel)
        {
            MM_KVLevel OutLevel;
            if (KVLevels.TryGetValue(KVLevel, out OutLevel))
                return OutLevel;
            else
                return KVLevels["Other KV"];
        }

        /// <summary>
        /// Build out our list of colors
        /// </summary>
        /// <param name="InString">Our incoming string of colors</param>
        /// <param name="Model">The model associated with the export</param>
        /// <returns></returns>        
        public static string WriteColorsAndModelSpecifics(string InString, MM_Database_Model Model)
        {
            //Load in our list of colors
            Dictionary<int, string> FGColors = new Dictionary<int,string>();
            String InLine;
            using (StringReader sRd = new StringReader(Resources.rgb))            
            while (!String.IsNullOrEmpty(InLine = sRd.ReadLine()))
            {
                string[] splStr = InLine.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                FGColors.Add(Color.FromArgb(int.Parse(splStr[0]), int.Parse(splStr[1]), int.Parse(splStr[2])).ToArgb(), splStr[3]);
            }

            //Build our list of substation and ctg navigators
            StringBuilder sKeysets = new StringBuilder();
            if (Model.Substations.Count == 0)
                foreach (CIM_Element Elem in Model.ElementsOfType("cim:Substation"))
                    Model.Substations.Add(Elem.Name, Elem);
            foreach (string Sub in Model.Substations.Keys)
            {
                sKeysets.AppendLine("\tkeyset \"NAV_SUB_" + Sub.ToUpper() + "\"");
                sKeysets.AppendLine("\t(");
                sKeysets.AppendLine("\t\tflash");
                sKeysets.AppendLine("\t\tkey(\"SELECT\")");
                sKeysets.AppendLine("\t\tcommand(\"display/app=%disapp%/fam=%disfam% " + Sub.ToUpper() + "\")");
                sKeysets.AppendLine("\t);");
                sKeysets.AppendLine();
            }

            //Build our list of ctg navigators
            foreach (CIM_Trace Trace in Model.Traces.Values)
            {
                sKeysets.AppendLine("\tkeyset \"NAV_B2B_" + Trace.Name.ToUpper() + "\"");
                sKeysets.AppendLine("\t(");
                sKeysets.AppendLine("\t\tflash");
                sKeysets.AppendLine("\t\tkey(\"SELECT\")");
                sKeysets.AppendLine("\t\tcommand(\"display/app=%disapp%/fam=%disfam% " + "__" + Trace.Name.ToUpper() + "\")");
                sKeysets.AppendLine("\t);");
                sKeysets.AppendLine();
            }

            foreach (MM_KVLevel KVLevel in KVLevels.Values)
                InString = InString.Replace("[" + KVLevel.Name.Replace(" ", "") + "Color" + "]", FGColors[KVLevel.Energized.ForeColor.ToArgb()]);
            InString = InString.Replace("{NavigationKeysets}", sKeysets.ToString());
            return InString;
        }
    }
}
